// 前端流程
$('#addProjectsBtn').click(function(){
    //获取专业名称
    const name = $('#addProjectsName').val();
    // console.log(name);
    $.ajax({
        url:('/subjects/createSubjects'),
        type:'POST',
        data:{
            name
        },
        success(res) {
            if(res.code){
                alert('新增成功');
            }else{
                alert('新增失败');
            }
        }
    })
})
showSubjects();
// 内容初始化
async function showSubjects(){
    const subjectsData = await getSubjectsData();
    console.log(subjectsData);
    subjectsTableRender(subjectsData);
    subjectsSelectRender(subjectsData);
    //根据专业获取班级
    getClassesBySubjectsId(subjectsData[0]._id);
}

//获取专业数据
function getSubjectsData(){
    return new Promise((resolve, reject) =>{
        $.ajax({
            url:'/subjects/getSubjects',
            type:'GET',
            success(res){
                if(res.code){
                    resolve(res.result);
                }
            }
        })
    })
}
//渲染专业数据
function subjectsTableRender(data){
    const subjectsHtml = data.map(item => {
        return`
        <div class="row">
                <span>${item._id}</span>
                <span>${item.name}</span>
                <span>
                    <a href="#">修改</a>
                    <a href="#">删除</a>
                </span>
            </div>
        `
    }).join('');
    $('.tbody').html(subjectsHtml);
}
//将专业数据渲染成 select 下拉列表
function subjectsSelectRender(data){
    const subjectsHtml =  data.map(item => `<option value="${item._id}">${item.name}</option>`).join('');
    $('#selectHeadTeacher').html(subjectsHtml);
    //渲染专业列表
    $('#studentsSubject').html(subjectsHtml);
}